//
//  HPLeftTopView.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/3.
//  Copyright © 2019 李文强. All rights reserved.
//

#import "HPLeftTopView.h"
#import "SYRequestAPI+HomePage.h"
#import "XGMessageModelOfMe.h"

@implementation HPLeftTopView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        [self initSubView];
        [self initOption];
        [self layout];
        [self getMessageList];
    }
    return self;
}
- (UIView *)top_view{
    if (!_top_view) {
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = [UIColor whiteColor];
        _top_view = view;
    }
    return _top_view;
}
- (UIImageView *)leftImageView{
    if (!_leftImageView) {
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"working"];
        _leftImageView = imageView;
    }
    return _leftImageView;
}
- (UILabel *)work_label{
    if (!_work_label) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"消息";
        _work_label = label;
    }
    return _work_label;
}
- (UILabel *)noDataLabel{
    if (!_noDataLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"当前消息为空╮(╯_╰)╭";
        label.textAlignment = 1;
        _noDataLabel = label;
    }
    return _noDataLabel;
}

//- (MinButtonViewBtn *)menu_Btn{
//    if (!_menu_Btn) {
//        MinButtonViewBtn *btn = [[MinButtonViewBtn alloc]initWithFrame:CGRectMake(0, 0, 0, 0) andType:ButtonImageInRight];
//        btn.bottomLabel.text = @"选择班级";
//        btn.topImage.image = [UIImage imageNamed:@"arrow_down"];
//        [btn addTarget:self action:@selector(arrow_click) forControlEvents:UIControlEventTouchUpInside];
//        btn.titleLabel.textAlignment = 2;
//        [btn.bottomLabel mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(@0);
//        }];
//        _menu_Btn = btn;
//    }
//    return _menu_Btn;
//}
- (void)initSubView{
    _messageListArray = [NSMutableArray new];
    self.userInteractionEnabled = YES;
    [self addSubview:self.top_view];
    [_top_view addSubview:self.leftImageView];
    [_top_view addSubview:self.work_label];
//    [_top_view addSubview:self.menu_Btn];
//    [self addLittleSubView];
    [self addSubview:self.tableList];
    [self addSubview:self.noDataLabel];
    [_tableList headerRefreshBlock:^{
        [self->_messageListArray removeAllObjects];
        [self getMessageList];
    }];
}
- (void)initOption{
    self.backgroundColor = [UIColor whiteColor];
}
- (void)layout{
    [_top_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.height.equalTo(@38);
    }];
    [_leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@17);
        make.centerY.equalTo(self.top_view.mas_centerY);
        make.width.equalTo(@20);
        make.height.equalTo(@20);
    }];
    [_work_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftImageView.mas_right).offset(13);
        make.centerY.equalTo(self.top_view.mas_centerY);
        make.width.equalTo(@60.5);
        make.height.equalTo(@15.0);
    }];
//    [_menu_Btn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.top_view.mas_right).offset(-15);
//        make.centerY.equalTo(self.top_view.mas_centerY);
//        make.width.equalTo(@100);
//        make.height.equalTo(@20);
//    }];
    [_noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
    [_tableList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@40);
        make.bottom.equalTo(@0);
    }];
}
#pragma mark - 点击箭头的方法
- (void)arrow_click{
    [self.myDelegate LeftClassClick];
}
#pragma mark - 添加子视图
- (void)addLittleSubView{
    for (int i = 0; i<4; i++) {
        CGFloat W = 204*fw;
        CGFloat H = 105*fh;
        CGFloat X = 15*(i%2+1)+W*(i%2);
        CGFloat Y = 15*(i/2)+H*(i/2)+56*fh;
        HPLTCellView *cellView = [[HPLTCellView alloc]initWithFrame:CGRectMake(X, Y, W, H)];
        cellView.tag = 20+i;
        cellView.hidden = YES;
        [self addSubview:cellView];
    }
    //没有数据
}
- (void)drawRect:(CGRect)rect{
    UIBezierPath *path = [[UIBezierPath alloc]init];
    [path moveToPoint:CGPointMake(0, 39)];
    [path addLineToPoint:CGPointMake(fw*452, 39)];
    [path setLineWidth:1];
    [LINCOLOR setStroke];
    [path stroke];
}
- (void)updateView{
    if (_dataArray.count == 0) {
        for (int i = 0; i<4; i++) {
            HPLTCellView *cell = (HPLTCellView *)[self viewWithTag:20+i];
            cell.hidden = YES;
        }
        return;
    }
    for (int i = 0; i<_dataArray.count; i++) {
        _noDataLabel.hidden = YES;
        TheNewWorkListModel *model = _dataArray[i];
        HPLTCellView *cellView = (HPLTCellView *)[self viewWithTag:20+i];
        cellView.hidden = NO;
        cellView.index = i;
        cellView.userInteractionEnabled = YES;
        cellView.titleLabel.attributedText =  [[NSMutableAttributedString alloc] initWithString:model.className attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: 14],NSForegroundColorAttributeName: TITLECOLOR}];
        cellView.teacherLabel.attributedText =[[NSMutableAttributedString alloc] initWithString:model.paperName attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: 12],NSForegroundColorAttributeName: TITLECOLOR}];
        cellView.timeLabel.attributedText =[[NSMutableAttributedString alloc] initWithString:model.upLoadDate attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang-SC-Regular" size: 12],NSForegroundColorAttributeName: TITLECOLOR}];
        NSString *str = [NSString stringWithFormat:@"应交：%@人 实交：%@人  ",model.classStudents,model.submitStudents];
        
        NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:str];
        //目的是想改变 ‘/’前面的字体的属性，所以找到目标的range
        NSRange range1 = [str rangeOfString:@"实交："];
        NSRange range2;
        NSRange pointRange;
        range2 = [str rangeOfString:@"人  "];
        pointRange = NSMakeRange(range1.location+3, range2.location-range1.location-3);
        [attribut addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:pointRange];
        //赋值
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[NSFontAttributeName] = [UIFont systemFontOfSize:12];
        [attribut addAttributes:dic range:pointRange];
        cellView.otherLabel.attributedText = attribut;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goZuoYeView:)];
//        [cellView addGestureRecognizer:tap];
    }
}
//- (void)goZuoYeView:(UITapGestureRecognizer *)gesture{
//    HPLTCellView *cellView = (HPLTCellView *)gesture.view;
//    TheNewWorkListModel *model = _dataArray[cellView.index];
//    self.goZuoYeBlock(model);
//}

#pragma mark - 更改为消息列表
- (UITableView *)tableList{
    if (!_tableList) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        [tableView registerClass:[HPLeftCell class] forCellReuseIdentifier:@"HPLeftCell"];
        _tableList = tableView;
    }
    return _tableList;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _messageListArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NoticeMessageList *model = _messageListArray[indexPath.row];
    NSDictionary *dic = dicWithJsonString(model.MsgContent);
    XGMessageModelOfMe *m = [XGMessageModelOfMe yy_modelWithJSON:dic];
    [self chuLiMessage:m];
}
#pragma mark - 异常处理
- (void)chuLiMessage:(XGMessageModelOfMe *)model{
    if ([model.type isEqualToString:@"101"]) {
        //考勤异常
        
        _kqycVC = [[SYKaoQinYiChangViewController alloc] init];
        _kqycVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _kqycVC.xgModel = model;
        [_kqycVC requestDataListArr];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_kqycVC.view];
    }else if ([model.type isEqualToString:@"102"]){
        //排名异常
        _loginHomePageVC = [[ChengJiYiChangVC alloc] init];
        _loginHomePageVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _loginHomePageVC.model = model;
        [_loginHomePageVC getPaiMingChengJiYiChangUp];
        [_loginHomePageVC getPaiMingChengJiYiChangDown];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_loginHomePageVC.view];
    }else if ([model.type isEqualToString:@"103"]){
        //错题率
        _cuoTiLvView = [[CuoTiLvVC alloc]init];
        _cuoTiLvView.msgId = model.msgId;
        [_cuoTiLvView getRequest];
         [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_cuoTiLvView.view];
//        [XSInfoView showInfo:@"此功能正在开发中..." onView:[UIApplication sharedApplication].keyWindow.rootViewController];
    }else if ([model.type isEqualToString:@"104"]){
        //成绩后三名
//        [XSInfoView showInfo:@"此功能正在开发中..." onView:[UIApplication sharedApplication].keyWindow.rootViewController];
        //成绩后三名
        _hsmVC = [[SYHouSanMingViewController alloc] init];
        _hsmVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
        _hsmVC.xgModel = model;
//        [_hsmVC requestData];
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_hsmVC.view];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HPLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HPLeftCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[HPLeftCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HPLeftCell"];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NoticeMessageList *model = _messageListArray[indexPath.row];
    cell.timeLabel.text = model.CreateDate;
    NSDictionary *dic = dicWithJsonString(model.MsgContent);
    cell.detailLabel.text = [dic objectForKey:@"body"];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, 0, 0);
    return view;
}
#pragma mark - 得到消息列表
- (void)getMessageList{
    [SYRequestAPI sy_getNoticeNoticeReceiveServiceGetNoticeInfo:@{} isUnread:NO success:^(id  _Nonnull responseObject) {
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            NoticeMessageList *model = [NoticeMessageList yy_modelWithJSON:dic];
            [self->_messageListArray addObject:model];
        }
        self->_noDataLabel.hidden = YES;
        [self->_tableList reloadData];
        [self->_tableList.mj_header endRefreshing];
    } fail:^(NSError *error) {
        [self->_tableList.mj_header endRefreshing];
    }];
}
#pragma 字符串转换成字典
NS_INLINE NSDictionary *dicWithJsonString(NSString *jsonString)
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
//        NSLog(@"json解析失败：%@",err);
        return nil;
    }
//     NSLog(@"得到消息列表 %@",dic);
    return dic;
}
@end
